import {Button, Form, message, Modal, Popconfirm, Spin, Table, Upload} from 'antd';
import React, {Component, useState} from 'react';
import {DownloadOutlined, UploadOutlined, WarningOutlined} from "@ant-design/icons";
import styles from "@/pages/Model/model.less";
import {TestDelete, TestList, TestUpload} from "@/services/A10/TestController";
import {ModelList, PredictedData, PredictedMultiData} from "@/services/A10/ModelController";
import * as echarts from "echarts";

class ExamplePage extends Component{

  state = {
    data: [],
    columns: [],
    loading:false,
    setLoading:false,
    selectedRowKeys:[],
    setSelectedRowKeys:[],
    ModelData:[],
    ModelColumns:[],
    ModelAndTestName: { testName: '', modelName: '' },
    showInput:false,
    showInput1:false,
    testname: [],
    ModelColumns1:[]
  }

  loadData = async () => {
    const data = await TestList();
    this.setState({ data });
  }

  async componentDidMount() {

    const data = await TestList();
    const ModelData = await ModelList();

    const columns = [
      {
        title: '测试文件列表',
        dataIndex: 'name',
        key: 'name',
        render: (text) => <a>{text}</a>,
      },
      {
        title: '文件大小',
        dataIndex: 'size',
        key: 'size',
      },
      {
        title: '测试',
        dataIndex: 'Download',
        key: 'Download',
        render:(text, record)=> {
          return (<Button type="primary" onClick={() =>this.handleButtonClick(record)} className={styles.ButtonInfo}>选择预测模型</Button>);
        },
      },
      {
        title: '删除',
        key: 'Delete',
        dataIndex: 'Delete',
        render:(text, record)=> {
          return (
            <Popconfirm
              title="确定要删除此文件吗?"
              onConfirm={() => this.handTestDelete(record)}
              icon={
                <WarningOutlined
                  style={{
                    color: 'red',
                  }}
                />
              }
            >
              <Button type="primary" danger>删除文件</Button>
            </Popconfirm>
          );
        },
      }
    ];

    const ModelColumns = [
      {
        title: '已训练模型列表',
        dataIndex: 'name',
        key: 'name',
        render: (text) => <a>{text}</a>,
      },
      {
        title: '预测',
        key: 'Predicted',
        dataIndex: 'Predicted',
        render:(text, record)=> {
          return (<Button type="primary" onClick={()=>this.handPredictedData(record)} className={styles.ButtonInfo}>预测数据</Button>);
        },
      }
    ];

    const ModelColumns1 = [
      {
        title: '已训练模型列表',
        dataIndex: 'name',
        key: 'name',
        render: (text) => <a>{text}</a>,
      },
      {
        title: '预测',
        key: 'Predicted',
        dataIndex: 'Predicted',
        render:(text, record)=> {
          return (<Button type="primary" onClick={()=>this.handPredictedMultiData(record)} className={styles.ButtonInfo}>预测数据</Button>);
        },
      }
    ];

    this.setState({ModelData});
    this.setState({ModelColumns});
    this.setState({ModelColumns1});
    this.setState({columns});
    this.setState({data});
  }

  handPredictedMultiData=(record) => {
    const modelname=record.name;
    const requestBody = {
      modelname: modelname,
      testnames: this.state.testname
    };
    this.setState({showInput1:false})
    const selectedRowKeys = [];
    this.setState({selectedRowKeys});
    this.setState({ loading: true });
    PredictedMultiData(requestBody).then((resp) => {
      if(resp.data=="success"){
        this.setState({ loading: false });
        message.success("数据预测完成");
      }else {
        message.error("模型预测失败");
      }
    });
  }


  handPredictedData =(record) => {
    const showInput = false;
    this.setState({ loading: true });
    const updatedModelAndTestName = { ...this.state.ModelAndTestName, modelName: record.name };
    this.setState({ showInput, ModelAndTestName: updatedModelAndTestName });
    PredictedData(updatedModelAndTestName).then((resp) => {
      if(resp.data=="success"){
        this.setState({ loading: false });
        message.success("数据预测完成");
      }else {
        message.error("模型预测失败");
      }
    });
  }

  handleButtonClick = (record) => {
    const showInput=true;
    const updatedModelAndTestName = { ...this.state.ModelAndTestName, testName: record.name };
    this.setState({ showInput, ModelAndTestName: updatedModelAndTestName });
  };

  closeButtonClick = () => {
    const showInput=false;
    const showInput1=false;
    this.setState({showInput,showInput1});
  };

  handUploadTest(formData){
    TestUpload(formData).then(() => this.loadData());
  }

  handTestDelete(record){
    TestDelete(record).then(() => this.loadData());
  }
  handleUpload = (info) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} 文件上传成功`);
      const formData = new FormData();
      formData.append('file', info.file.originFileObj, info.file.name); // 将文件数据添加到 formData 对象中
      this.handUploadTest(formData);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }
  }


  start = () => {
    const showInput1=true;
    const testname=this.state.selectedRowKeys;
    this.setState({testname,showInput1});
    console.log(this.state.testname);
  };

  onSelectChange = (newSelectedRowKeys) => {
    this.setState({ selectedRowKeys: newSelectedRowKeys });
  };



  render() {
    const { data ,columns,selectedRowKeys,showInput,
      ModelColumns,ModelData,showInput1,ModelColumns1} = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => ({
        // 将每行的 name 添加为 checkbox 的 value 值
        value: record.name,
        // 根据数据中的 name 字段判断是否选中
        checked: selectedRowKeys.includes(record.name),
      }),
    };
    const hasSelected = selectedRowKeys.length > 0;
    return (
      <Spin
        size={"large"}
        spinning={this.state.loading}
        tip={<span style={{ color: '#1890ff', fontSize: '18px' }}>数据预测中.....</span>}
        style={{ display: 'flex',alignItems: 'center', marginTop: '150px' }}
      >
      <div>
        <div
          style={{
            marginBottom: 16,
          }}
        >
          <Button type="primary" onClick={this.start} disabled={!hasSelected}>
            批量预测
          </Button>
          <span
            style={{
              marginLeft: 8,
            }}
          >
          {hasSelected ? `选择了 ${selectedRowKeys.length} 个模型` : ''}
        </span>
        </div>
        <Table rowSelection={rowSelection} columns={columns} dataSource={data} rowKey="name" />

        <Upload  showUploadList={false} onChange={this.handleUpload} multiple={true}>
          <Button icon={<UploadOutlined />} className={styles.train}>上传测试文件</Button>
        </Upload>
        <Modal
          open={showInput}
          cancelText="取消"
          onCancel={() => {this.closeButtonClick();}}
          okButtonProps={{ style: { display: 'none' } }}
        >
          <Form
            layout="vertical"
            name="form_in_modal"
            initialValues={{
              modifier: 'public',
            }}
          >
            <Form.Item>
              <Table columns={ModelColumns} dataSource={ModelData}></Table>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          open={showInput1}
          cancelText="取消"
          onCancel={() => {this.closeButtonClick();}}
          okButtonProps={{ style: { display: 'none' } }}
        >
          <Form
            layout="vertical"
            name="form_in_modal"
            initialValues={{
              modifier: 'public',
            }}
          >
            <Form.Item>
              <Table columns={ModelColumns1} dataSource={ModelData}></Table>
            </Form.Item>
          </Form>
        </Modal>
      </div>
      </Spin>
    );
  }

}

export default ExamplePage;
